package cn.sanshuilin.kst.system.provider.serviceimpl;

import cn.sanshuilin.kst.common.redis.RedisRepository;
import cn.sanshuilin.kst.common.utils.HttpUtil;
import cn.sanshuilin.kst.common.utils.RandomHelper;
import cn.sanshuilin.kst.system.api.exception.InvalidCaptchaException;
import cn.sanshuilin.kst.system.api.exception.base.BusinessException;
import cn.sanshuilin.kst.system.api.service.ISmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author greenlee
 * @version v1.0
 * @create 创建时间: 2018-01-24 20:59
 * Copyright 2017  by 三水林科技有限公司
 **/
@Service("smsService")
public class SmsService implements ISmsService {
    /**
     * redis repository
     */
    @Autowired
    private RedisRepository redisRepository;
    /**
     * 缓存前缀
     */
    private static final String REDIS_PREFIX = "captcha_";
    @Override
    public void sendValidCodeToMobile(String strMobile, String strValidCode) throws BusinessException {
        //存入 Redis
        long time = 1L; //15分钟有效期
        redisRepository.setExpire(REDIS_PREFIX + strMobile, strValidCode, time * 60); //15分钟有效期
//        HttpUtil.sendSMS(strMobile,code);
        System.out.printf("向 %s 发送短信验证码\n", strMobile);
        System.out.printf("您的验证码为：%s，有效期：%s 分钟\n", strValidCode, time);
    }

    @Override
    public String createRandomCode(int n) {
        String code = RandomHelper.getRandNum(n); //验证码
        return code;
    }

    @Override
    public void validCaptcha(String mobile, String captcha) throws InvalidCaptchaException {
        String code = redisRepository.get(REDIS_PREFIX + mobile);
        if (!captcha.equals(code)) {
            throw new InvalidCaptchaException(String.format("验证码 '%s' 无效", captcha));
        }
    }
}
